package com.xl6667.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl6667.constants.SystemConstants;
import com.xl6667.domain.ResponseResult;
import com.xl6667.domain.dto.PageDto;
import com.xl6667.domain.dto.SysUserDto;
import com.xl6667.domain.dto.UserInfoDto;
import com.xl6667.domain.entity.User;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.exception.SystemException;
import com.xl6667.mapper.UserMapper;
import com.xl6667.service.UserService;
import com.xl6667.util.BeanCopyUtil;
import com.xl6667.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService  {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult getUserInfo() {
        Long userId = SecurityUtil.getUserId();
        User user = getById(userId);
        UserInfoDto userInfoDto = BeanCopyUtil.copyBean(user, UserInfoDto.class);
        return ResponseResult.okResult(userInfoDto);
    }

    @Override
    public ResponseResult updateUser(User user) {
        updateById(user);
        return ResponseResult.okResult("修改成功");

    }

    @Override
    public ResponseResult register(User user) {
        if (!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //用户名是否重复
        if (!userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //是否有密码
        if (!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }

        //是否有邮箱
        if (!StringUtils.hasText(user.getEmail()) || !Validator.isEmail(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        //邮箱是否存在
        if (!emailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //是否有昵称，没有将用户名当昵称
        if (!StringUtils.hasText(user.getNickName())){
            user.setNickName(user.getUserName());
        }

        //对密码进行加密，调用security的加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //添加用户
        save(user);

        return ResponseResult.okResult("注册成功");
    }

    @Override
    public ResponseResult getUserList(Integer pageNum,Integer pageSize,String userName,String phonenumber,String status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getDelFlag, SystemConstants.DEL_FLAG_NORMA);

        queryWrapper.like(StringUtils.hasText(userName),User::getUserName,userName);
        queryWrapper.eq(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber);
        queryWrapper.eq(StringUtils.hasText(status),User::getStatus,status);
        Page<User> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        List<User> list = page.getRecords();
        List<SysUserDto> sysUserDtos = BeanCopyUtil.copyBeanList(list, SysUserDto.class);
        PageDto pageDto = new PageDto(sysUserDtos,page.getTotal());
        return ResponseResult.okResult(pageDto);
    }

    @Override
    public ResponseResult delUser(Long id) {
        Long userId = SecurityUtil.getUserId();
        if (userId!=null && !userId.equals(id) ){
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId,id).set(User::getDelFlag,SystemConstants.DEL_FLAG);
            update(null,updateWrapper);
            return ResponseResult.okResult("删除成功");
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"不能删除当前用户");
    }

    @Override
    public ResponseResult changeStatusUser(User user) {

        updateById(user);
        return ResponseResult.okResult("修改成功");
    }

    private  boolean emailExist(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,email);
        User one = getOne(queryWrapper);
        return Objects.isNull(one);
    }

    private  boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User one = getOne(queryWrapper);
        return Objects.isNull(one);
    }

}
